package async;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Field;
import jdk.internal.vm.Continuation;
import jdk.internal.vm.ContinuationScope;
import sun.misc.Unsafe;

// 3303 ms, r = 4995000000 java --enable-preview --add-opens java.base/jdk.internal.vm=ALL-UNNAMED -Xlog:gc=info,gc+heap=info:gc_loom.log:time async.Loom4Test
@SuppressWarnings("deprecation")
public class Loom4Test {
	private static final ContinuationScope cs = new ContinuationScope("VirtualThreads");
	private static final Unsafe U;
	private static final long CONT_OFFSET;
	private static final MethodHandle DO_YIELD;
	private static final MethodHandle ENTER_SPECIAL;
	private static final int N1 = 100;
	private static final int N2 = 100;
	private static final int N3 = 1000;
	private static final int N = N1 * N2 * N3;
	private static int s_i;

	static {
		try {
			Field theUnsafeField = Unsafe.class.getDeclaredField("theUnsafe");
			theUnsafeField.setAccessible(true);
			U = (Unsafe)theUnsafeField.get(null);
			long OVERRIDE_OFFSET;
			for (long i = 8; ; i++) {
				if (U.getBoolean(theUnsafeField, i)) {
					theUnsafeField.setAccessible(false);
					if (!U.getBoolean(theUnsafeField, i)) {
						OVERRIDE_OFFSET = i;
						break;
					}
					theUnsafeField.setAccessible(true);
				}
				if (i == 32) // should be enough
					throw new UnsupportedOperationException(System.getProperty("java.version"));
			}

			var f = Thread.class.getDeclaredField("cont");
			U.putBoolean(f, OVERRIDE_OFFSET, true); // f.setAccessible(true);
			CONT_OFFSET = U.objectFieldOffset(f);
			var m = Continuation.class.getDeclaredMethod("doYield");
			U.putBoolean(m, OVERRIDE_OFFSET, true);
			DO_YIELD = MethodHandles.lookup().unreflect(m);
			m = Continuation.class.getDeclaredMethod("enterSpecial", Continuation.class, boolean.class, boolean.class);
			U.putBoolean(m, OVERRIDE_OFFSET, true);
			ENTER_SPECIAL = MethodHandles.lookup().unreflect(m);
		} catch (ReflectiveOperationException e) {
			throw new RuntimeException(e);
		}
	}

	static void pause() {
		var c = U.getObject(Thread.currentThread(), CONT_OFFSET);
		try {
			@SuppressWarnings("unused")
			var __ = (int)DO_YIELD.invokeExact();
			U.storeFence(); // needed to prevent certain transformations by the compiler
		} catch (Throwable e) {
			throw new RuntimeException(e);
		} finally {
			U.putObject(Thread.currentThread(), CONT_OFFSET, c);
		}
	}

	static void resume(Continuation c) {
		if (c.isDone())
			throw new IllegalStateException("Continuation terminated");
		try {
			ENTER_SPECIAL.invokeExact(c, true, false);
		} catch (Throwable e) {
			throw new RuntimeException(e);
		}
	}

	private static void f3() {
		for (int i = 0; i < N3; i++) {
			s_i = i;
			pause();
		}
	}

	private static void f2() {
		for (int i = 0; i < N2; i++)
			f3();
	}

	private static void f1() {
		for (int i = 0; i < N1; i++)
			f2();
	}

	public static void main(String[] args) throws Exception {
		long t = System.nanoTime();
		var c = new Continuation(cs, Loom4Test::f1);
		c.run();
		long r = 0;
		for (int i = 0; ; ) {
			r += s_i;
			if (++i >= N)
				break;
			resume(c);
		}
		System.out.println((System.nanoTime() - t) / 1_000_000 + " ms, r = " + r);
	}
}
